/* 
 * Copyright 2013 Imanuel Rohlfing, Dennis Wittkötter

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package management.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import management.entities.Person;
import org.primefaces.component.picklist.PickList;
import org.primefaces.model.DualListModel;

/**
 * Converter for person picklists.
 * Converts a person object to String or a string to a person.
 * @author Dennis Wittkötter
 */
@FacesConverter("personConverter")
public class PersonConverter implements Converter {

    /**
     * Converts a string into a person object.
     * 
     * @param arg0 FacesContext
     * @param arg1 gui element that initiates the conversion
     * @param arg2 the string that shall be converted
     * @return  the conversion result as a person object
     */
    @Override
    public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
        Object ret = null;
        if (arg1 instanceof PickList) {
            Object dualList = ((PickList) arg1).getValue();
            DualListModel dl = (DualListModel) dualList;
            for (Object o : dl.getSource()) {                                  
                String id = "";
                id += ((Person) o).getIdentityCardNumber();
                if (arg2.equals(id)) {
                    ret = o;
                    break;
                }
            }
            if (ret == null) {
                for (Object o : dl.getTarget()) {
                    String id = "";
                    id += ((Person) o).getIdentityCardNumber();
                    if (arg2.equals(id)) {
                        ret = o;
                        break;
                    }
                }
            }
        }
        return ret;
    }

    /**
     * Converts a person object to a string.
     * 
     * @param arg0 FacesContext
     * @param arg1 gui element which initiates the conversion
     * @param arg2 the person object that shall be converted
     * @return  the conversion result as a string
     */
    @Override
    public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
        String str = "" + ((Person) arg2).getIdentityCardNumber();
        return str;
    }
}
